#include "CG_ff_grid.h"




CG_ff_grid::~CG_ff_grid(void)
{
	this->myGrid.clear();
}


bool CG_ff_grid::CG_ff_grid_insert(CG_flip_flop *ff)
{
	std::pair<ff_map_iter, bool> res;
	CG_coord new_coord;

	if(NULL == ff)
	{
		return false;
	}

	if(this->myGrid.size() >= this->myGrid.max_size())
	{
		return false;
	}

	new_coord.x = ff->get_loc_x();
	new_coord.y = ff->get_loc_y();
	
	try
	{
		res = this->myGrid.insert(std::pair<const CG_coord, CG_flip_flop>(new_coord, *ff));
	}
	catch(std::exception e)
	{
		std::clog<< "Exception: " << e.what() << endl;
		delete ff;
		return false;
	}
	if(false == res.second)
	{
		std::clog<< "CG_ff_grid_insert: insertion failed" << endl;
		delete ff;
		return false;
	}

	return true;
}


long CG_ff_grid::CG_ff_grid_get_size()
{
	return this->myGrid.size();
}


CG_flip_flop *CG_ff_grid::CG_ff_grid_get_element_by_id(long anID)
{
	ff_map_iter it;

	if(anID < 0)
	{
		return NULL;
	}

	for(it = this->myGrid.begin(); it != myGrid.end(); it++)
	{
		if((*it).second.get_ID() == anID)
		{
			return &((*it).second);
		}
	}

	return NULL;
}

CG_flip_flop *CG_ff_grid::CG_ff_grid_get_first() {
	if (myGrid.empty()) 
	{
		return NULL;
	}
	ff_map_iter it = myGrid.begin();
	return &((*it).second);
}

CG_flip_flop *CG_ff_grid::CG_ff_grid_get_next(CG_flip_flop *ff)
{
	ff_map_iter it;
	CG_coord c;

	if(NULL == ff)
	{
		return NULL;
	}
	if(ff->get_ID() < 0)
	{
		return NULL;
	}

	c.x = ff->get_loc_x();
	c.y = ff->get_loc_y();
	it = this->myGrid.find(c);
	while (it != myGrid.end()) {
		CG_flip_flop *this_ff = &((*it++).second);
		if (this_ff != ff) 
		{
			return this_ff;
		}
	}
	return NULL;
}